#include<iostream>
#include"Sock.hpp"
#include"Protocol.hpp"
using namespace std;

//版本2:
void Usage(string proc)
{
    cout << "Usage: " << proc << " server_ip server_port" << endl;
} 
//之后我们是这样运行:  ./CalClient server_ip server_port
int main(int argc,char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    int sock = Sock::Socket();//创建套接字
    //进行连接, Connect函数内部会帮我们转化,如:字符串IP->整数IP 主机序->网络序
    Sock::Connect(sock, argv[1], atoi(argv[2]));

    //业务逻辑
    request_t req;
    memset(&req, 0, sizeof(req));
    cout << "Please Enter Data One# ";//输入第一个数据
    cin >> req.x;
    cout << "Please Enter Data Two# ";//输入第二个数据
    cin >> req.y;
    cout << "Please Enter operator# ";//输入操作符
    cin >> req.op;

    //先把请求序列化再发送
    string json_string = SerializeRequest(req);
    ssize_t s = write(sock, json_string.c_str(), json_string.size());//发送序列化之后的请求

    //读取返回结果
    char buffer[1024];
    s = read(sock, buffer, sizeof(buffer) - 1);
    if (s > 0)
    {
        response_t resp;
        buffer[s] = 0;//末尾置\0
        std::string str = buffer;
        cout <<"收到的响应是(反序列化):"<<str<<endl;
        DeserializeResponse(str, resp);//先对响应进行反序列化
        cout <<"收到的响应是(序列化):"<<str<<endl;

        cout << "code[0:success]: " << resp.code << endl;
        cout << "result: " << resp.result << std::endl;
    }
    return 0;
}

//版本1：
/*
void Usage(string proc)
{
    cout << "Usage: " << proc << " server_ip server_port" << endl;
} 
//之后我们是这样运行:  ./CalClient server_ip server_port
int main(int argc,char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    int sock = Sock::Socket();//创建套接字
    //进行连接, Connect函数内部会帮我们转化,如:字符串IP->整数IP 主机序->网络序
    Sock::Connect(sock, argv[1], atoi(argv[2]));

    //业务逻辑
    request_t req;
    memset(&req, 0, sizeof(req));
    cout << "Please Enter Data One# ";//输入第一个数据
    cin >> req.x;
    cout << "Please Enter Data Two# ";//输入第二个数据
    cin >> req.y;
    cout << "Please Enter operator# ";//输入操作符
    cin >> req.op;

    //发送请求
    ssize_t s = write(sock, &req, sizeof(req));

    //读取返回结果
    response_t resp;
    s = read(sock, &resp, sizeof(resp));
    if (s == sizeof(resp))//读取到了完整的结果
    {
        //code只有0才代表成功,其他值表示遇到错误
        cout << "Only code==0 is success! Now code is: " << resp.code << endl;
        cout << "result: " << resp.result << std::endl;//计算结果
    }
    else
    {
        cout <<"读取失败"<<endl;
    }
    return 0;
}

*/